package cn.itsource.xhy.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    /*
     * 前置拦截器，接受请求后 执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // 获取请求头
        String token = request.getHeader("TOKEN");
        if (token!=null){
            // 使用token获取服务器中的数据
            Object o = redisTemplate.opsForValue().get(token);
            // 判断是否有值
            if (o!=null){
                // 刷新过期时间
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 设置响应头的字符集
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 响应数据 {"success":false,"message":"noAuth"}
        out.println("{\"success\":false,\"message\":\"noAuth\"}");
        return false;
    }
}
